<template>
    <div style="padding-top:30px">
        <el-form :model="dataForm" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
            <el-form-item size="mini" label="授权">
                <el-tree ref="menuListTree" :data="data2" show-checkbox node-key="menuId" :default-expand-all="true" :props="defaultProps">
                </el-tree>
            </el-form-item>
        </el-form>
        <div class="dialog-footer">
            <el-button @click="$router.go(-1)">取消</el-button>
            <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
        </div>
    </div>
</template>
<script>
import API from '@/api';
import cloneDeep from 'lodash/cloneDeep';
export default {
    data() {
        return {
            dataForm: {},
            data2: [],
            nodes:[],
            defaultProps: {
                children: 'children',
                label: 'title',
                value: 'menuId'
            }
        };
    },
    mounted() {
        this.getTreeData(this.$route.query.roleId);
    },
    methods: {
        getTreeData(id) {
            API.role.roleTreeMenu({ roleId: id }).then(res => {
                var data = res.result;
                this.nodesDeal(data);
                this.data2 = data;
            });
        },
        nodesDeal(data) {
            if (data.length > 0) {
                for (var k in data) {
                    if (data[k].children && data[k].children.length > 0) {
                        this.nodesDeal(data[k].children);
                    } else {
                        if (data[k].selected) {
                            this.nodes.push(data[k].menuId);
                        }
                    }
                }
            }
            this.$refs.menuListTree.setCheckedKeys(this.nodes);
        },

        // 表单提交
        dataFormSubmit() {
            console.log(this.$refs.menuListTree.getCheckedKeys());
            console.log(this.$refs.menuListTree.getHalfCheckedKeys());

            var params = {
                menuIds: this.$refs.menuListTree.getCheckedKeys().concat(this.$refs.menuListTree.getHalfCheckedKeys()),
                roleId: this.$route.query.roleId
            };
            console.log(params)
            API.role.saveRoleTreeMenu(params).then(data => {
                if (data.code == '0000') {
                    this.$message({
                        message: '操作成功',
                        type: 'success',
                        duration: 1500,
                        onClose: () => {
                            this.$refs.menuListTree.setCheckedKeys([]);
                            this.$router.go(-1);
                        }
                    });
                }
            });
        }
    }
};
</script>
<style>
.dialog-footer {
    text-align: center;
}
</style>